package com.quick.proxy.core.utils;

import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * Description: 字节处理工具类
 * Author: 吃素不吃肉
 * Date: 2023/7/4
 *
 * @author 吃素不吃肉
 */
public class ByteUtils {
    public static byte getBcc(byte[] bytes) {
        byte temp = bytes[0];
        for (int i = 1; i < bytes.length; ++i) {
            temp ^= bytes[i];
        }
        return temp;
    }

    public static byte[] mergeArrays(byte[]... arrays) {
        int totalLength = 0;
        for (byte[] array : arrays) {
            totalLength += array.length;
        }
        byte[] result = Arrays.copyOf(arrays[0], totalLength);
        int offset = arrays[0].length;
        for (int i = 1; i < arrays.length; i++) {
            System.arraycopy(arrays[i], 0, result, offset, arrays[i].length);
            offset += arrays[i].length;
        }
        return result;
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();

        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    }

    public static String intToHex(int number, int length) {
        StringBuilder hexString = new StringBuilder(Integer.toHexString(number));
        // 如果十六进制字符串长度小于指定长度,在前面添加零补齐
        while (hexString.length() < length * 2) {
            hexString.insert(0, "0");
        }
        return hexString.toString();
    }

    public static byte[] hexToBytes(String hexString) {
        if (hexString.length() == 1) {
            hexString = "0" + hexString;
        }
        int length = hexString.length();
        byte[] bytes = new byte[length / 2];

        for (int i = 0; i < length; i += 2) {
            String hex = hexString.substring(i, i + 2);
            bytes[i / 2] = (byte) Integer.parseInt(hex, 16);
        }
        return bytes;
    }

    public static String hexToString(String hex) {
        byte[] byteArray = DatatypeConverter.parseHexBinary(hex);
        return new String(byteArray, StandardCharsets.UTF_8);
    }
}
